export default {
    // 全局保存订阅者
    subscribers: {},
    // 订阅器
    subscribe: function(topic, subscriber) {
        if (!this.subscribers[topic]) {
            this.subscribers[topic] = []
        }
        this.subscribers[topic].push(subscriber)
    },
    // 发布器
    publish: function(topic, message) {
        if (!this.subscribers[topic]) {
            return
        }

        this.subscribers[topic].forEach(subscriber => {
            subscriber(topic, message)
        })
    },
    // 取消订阅
    unsubscribe: function(topic, subscriber) {
        if (!this.subscribers[topic]) {
            return
        }

        const index = this.subscribers[topic].indexOf(subscriber)
        if (index > -1) {
            this.subscribers[topic].splice(index, 1)
        } 
    }
}